# gozerlib/aliases.py
#
#

""" 
    command aliases. this module contains the aliases of commands. aliases
    are stored in the gozerstore/aliases json file. 

"""

## basic imports

import os

def aliasreverse(what):

    """ 
        get the reverse of an alias. 

        :param what: alias to get command for
        :type what: string

    """

    aliases = getaliases()

    for i, j in aliases.data.iteritems():
        if what == j:
            return i

def aliascheck(ievent):

    """ 
        check if alias is available.

        :param ievent: event to check for aliases

    """

    try:
        aliases = getaliases()
        cmnd = ievent.txt.split()[0]
        alias = aliases.data[cmnd]
        ievent.txt = ievent.txt.replace(cmnd, alias, 1)
        ievent.alias = alias
        ievent.aliased = cmnd
        ievent.makeargs()

    except (IndexError, KeyError):
        pass

def aliasset(fromm, to):

    """ 
        set an alias. 

        :param from: alias to set
        :type from: string
        :param to: command to alias 
        :type to: string

    """
    aliases = getaliases()
    aliases.data[fromm] = to

def aliasdel(fromm):

    """ 
        delete an alias.

        :param fromm: alias to delete
        :type fromm: string

    """

    try:
        aliases = getaliases()
        del aliases.data[fromm]
        aliases.save()
        return 1

    except KeyError:
        pass

def aliasget(fromm):

    """ 
        retrieve an alias. 

        :param fromm: alias to get command for
        :type fromm: string

    """

    aliases = getaliases()

    if aliases.data.has_key(fromm): 
        return aliases.data[fromm]

# the aliases object

aliases = None

def getaliases():

    """ get the aliases object constructed from db backend. """

    global aliases

    if not aliases:

        from gozerlib.persist.persist import Persist
        aliases =  Persist('gozerstore' + os.sep + 'aliases')

        if not aliases.data:
            aliases.data = {}

    return aliases
